package com.tianbao54.observer;

import java.util.ArrayList;
import java.util.List;

class Subject {

    private List<Observer> observerList = new ArrayList<Observer>();

    int state;

    public void addObserver (Observer observer) {
        observerList.add(observer);
    }

    public void updateState (int state) {
        this.state = state;
        notifyAllObserver();
    }

    public void removeObserver (Observer observer) {
        observerList.remove(observer);
    }

    public void notifyAllObserver () {
        observerList.forEach(observer -> observer.update());
    }

}

abstract class Observer {
    Subject subject = null;
    public abstract void update ();
}

class BinaryObserver extends Observer {

    BinaryObserver (Subject subject) {
        this.subject = subject;
        this.subject.addObserver(this);
    }

    @Override
    public void update() {
        System.out.println("binary observer : " + Integer.toBinaryString(subject.state));
    }
}

class HexObserver extends Observer {

    HexObserver (Subject subject) {
        this.subject = subject;
        this.subject.addObserver(this);
    }

    @Override
    public void update() {
        System.out.println("hex observer : " + Integer.toHexString(subject.state));
    }
}

public class ObserverPattern {

    public static void main(String[] args) {
        Subject subject = new Subject();
        new BinaryObserver(subject);
        new HexObserver(subject);
        subject.updateState(12);
    }
}